import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { Logger } from '@nestjs/common';

const logger = new Logger('LoggingInterceptor');
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const httpContext = context.switchToHttp();
    const request = httpContext.getRequest();
    const path = request.path;
    logger.log(`Request ${path} Begin`);
    const now = Date.now();
    // Log : 通用日志，按需进行记录(打印)
    // Warning:警告日志，比如: 尝试多次进行数据库操作
    // Error:产重日志，比如:数据库异常
    // Debug: 调试日志，比如:加载数据日志
    // Verbose:详细日志，所有的操作与详细信息(非必要不打印)
    return next
      .handle()
      .pipe(
        tap(() =>
          logger.log(`Request ${path} Done. used time ${Date.now() - now}ms`),
        ),
      );
  }
}
